﻿namespace Jhong.FunMVCBlog.Core.Data
{
    using Jhong.Data.Core.Common;
using Jhong.FunMVCBlog.Core.Entity;
using Jhong.FunMVCBlog.Core.Enum;
using Jhong.FunMVCBlog.Core.Infrastructure;
using System;
using System.Collections.Generic;

    public class ArticlesData : BaseData
    {
        public bool UpdateArticle(Articles model, string tagNames)
        {
            using (this._dbContext)
            {
                this._dbContext.BeginTranslation();
                try
                {
                    this._dbContext.UpdateEntity(model);
                    this._dbContext.T("DELETE FROM article_tag WHERE ArticleID=@0", model.ID).Execute();
                    this.UpdateArticleTag(model, tagNames,this._dbContext);
                    this._dbContext.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    this._dbContext.Rollback();
                    this._logData.AddLog(LogType.Exception, LogFrom.Admin, ex);
                    return false;
                }
            }
        }

        public bool InsertArticle(Articles model, string tagNames)
        {
            using (this._dbContext)
            {
                this._dbContext.BeginTranslation();
                try
                {
                    this._dbContext.InsertEntity(model);
                    this.UpdateArticleTag(model, tagNames,this._dbContext);
                    this._dbContext.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    this._dbContext.Rollback();
                    this._logData.AddLog(LogType.Exception, LogFrom.Admin, ex);
                    return false;
                }
            }
        }

        private void UpdateArticleTag(Articles model, string tagNames,DBContext dbContext)
        {
            foreach (var tag in tagNames.Split(','))
            {
                if (string.IsNullOrWhiteSpace(tag)) continue;
                var res1 = this._dbContext.T("SELECT * FROM tag WHERE Name=@0 and IsDelete=@0", tag, DeleteStatus.No).QueryFirstOrDefault<Tag>();
                Guid tID;
                if (null == res1)
                {
                    var tmodel = new Tag()
                    {
                        ID = Guid.NewGuid(),
                        CreateTime = DateTime.Now,
                        IsDelete = DeleteStatus.No,
                        LastModifyTime = DateTime.Now,
                        Name = tag
                    };
                    tID = tmodel.ID;
                    dbContext.InsertEntity(tmodel);
                }
                else
                {
                    tID = res1.ID;
                }
                dbContext.InsertEntity(new ArticleTag() { ArticleID = model.ID, TagID = tID });
            }
        }

        public Articles GetByID(Guid id)
        {
            using (this._dbContext)
            {
                return this._dbContext.T("select * from articles where ID=@0", id).QueryFirstOrDefault<Articles>();
            }
        }

        public string GetAllTags(Guid id)
        {
            using (this._dbContext)
            {
                var res = this._dbContext.T("SELECT t.* FROM tag t INNER JOIN article_tag a on a.TagID=t.ID AND a.ArticleID=@0 WHERE t.IsDelete=@1", id, DeleteStatus.No).QueryToEntitys<Tag>();
                var list = new List<string>();
                foreach (var r in res) list.Add(r.Name);
                return string.Join(",", list);
            }
        }

        public PageContainer<Articles> GetList(int pageIndex, int itemsPerPage)
        {
            if (pageIndex < 1) pageIndex = 1;
            if (itemsPerPage < 1) itemsPerPage = 10;
            using (this._dbContext)
            {
                var items = this._dbContext.T("SELECT ID,Title,CreateTime,LastModifyTime,IsPublist,IsTop FROM articles WHERE IsDelete=@0  ORDER BY IsTop DESC , CreateTime Desc LIMIT @1,@2", DeleteStatus.No, (pageIndex - 1) * itemsPerPage, itemsPerPage).QueryToEntitys<Articles>();
                var totalCount = this._dbContext.T("SELECT count(*) FROM articles WHERE IsDelete=@0 ", DeleteStatus.No).QueryFirstOrDefault<int>();
                var container = new PageContainer<Articles>(pageIndex, itemsPerPage, totalCount, items);
                return container;
            }
        }

        public bool DeleteArticle(Articles model)
        {
            using (this._dbContext)
            {
                try
                {
                    {
                        this._dbContext.BeginTranslation();
                        this._dbContext.DeleteEntity(model);
                        this._dbContext.T("DELETE FROM article_tag WHERE ArticleID=@0", model.ID).Execute();
                        this._dbContext.Commit();
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    this._dbContext.Rollback();
                    this._logData.AddLog(LogType.Exception, LogFrom.Admin, ex);
                    return false;
                }
            }
        }

        public IList<Articles> GetLastArticles(int num)
        {
            using (this._dbContext)
            {
                return this._dbContext.T("SELECT ID,Title from articles WHERE IsDelete=@0 AND IsPublist=@1 ORDER BY PublishTime DESC LIMIT @2", DeleteStatus.No, PublishStatus.Publish, num).QueryToEntitys<Articles>();
            }
        }

        public IList<Articles> GetIndexPage(int page, int count)
        {
            using (this._dbContext)
            {
                return this._dbContext.T("SELECT ID,Title,Summary,CategoryID,PublishTime FROM articles WHERE IsPublist=@0 and CategoryID not in(SELECT ID from category WHERE IsShow=@3) ORDER BY PublishTime DESC LIMIT @1,@2", PublishStatus.Publish, (page - 1) * count, count + 1, ShowStatus.Hide).QueryToEntitys<Articles>();
            }
        }
        public IList<Articles> GetIndexPage(int page, int count,Guid cid)
        {
            using (this._dbContext)
            {
                return this._dbContext.T("SELECT ID,Title,Summary,CategoryID,PublishTime FROM articles WHERE IsPublist=@0 and CategoryID=@4 and CategoryID not in(SELECT ID from category WHERE IsShow=@3) ORDER BY PublishTime DESC LIMIT @1,@2", PublishStatus.Publish, (page - 1) * count, count + 1, ShowStatus.Hide,cid).QueryToEntitys<Articles>();
            }
        }
        
    }
}